import React from 'react'

import { BrowserRouter as Router, Route, Link, Redirect, withRouter }
  from 'react-router-dom'

function Public() {
  return <h3>Public</h3>
}

function Protected() {
  return <h3>Protected</h3>
}

function PrivateRoute({ component: Component, ...rest }) {
  return (
    <Route {...rest} render={props =>
      fakeAuth.isAuthenticated ? (
        <Component {...props} />
      ) : (
          <Redirect to={{
            pathname: '/login',
            state: { from: props.location }
          }} />)
    } />
  )
}

const fakeAuth = {
  isAuthenticated: false,
  authenticate(cb) {
    this.isAuthenticated = true
    setTimeout(cb, 100)
  },
  signout(cb) {
    this.isAuthenticated = false,
      setTimeout(cb, 100)
  }
}

const AuthButton = withRouter(
  ({ history }) => fakeAuth.isAuthenticated ? (
    <p>Welcome!{" "}
      <button onClick={() => fakeAuth.signout(() => history.push("/"))}>
        Logout
      </button>
    </p>
  ) : (<p>You are not logged in.</p>))

class Login extends React.Component {
  state = {redireactToReferrer: false}

  login = () => {
    fakeAuth.authenticate(()=>{
      this.setState({redireactToReferrer: true})
    })
  }

  render() {
    let {from} = this.props.location.state || {from: {location: '/'}}
    let {redireactToReferrer} = this.state

    if(redireactToReferrer) {
      return <Redirect to={from}/>
    }

    return (
      <div>
        <p>You must log in to view the page at {from.pathname}</p>
        <button onClick={this.login}>Log in</button>
      </div>
    )
  }
}

export default function AuthExample() {
  return (
    <Router>
      <div>
        <AuthButton />
        <ul>
          <Li><Link to="/public">Public Page</Link></Li>
          <Li><Link to="/protected">Protected Page</Link></Li>
        </ul>
        <Route path="/public" component={Public} />
        <Route path="/login" component={Login} />
        <PrivateRoute path="/protected" component={Protected} />
      </div>
    </Router>
  )
}